class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i <= n - 3;) {
            for (int j = i + 1; j < n - 2;) {
                int right = n - 1, left = j + 1;
                while (left < right) {
                    long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        result.add(Arrays.asList(nums[i], nums[j], nums[right--], nums[left++]));
                        while (right > left && nums[right] == nums[right + 1])
                            right--;
                        while (right > left && nums[left - 1] == nums[left])
                            left++;
                    }
                }
                j++;
                while (j <= n - 2 && nums[j] == nums[j - 1])
                    j++;
            }
            i++;
            while (i <= n - 3 && nums[i] == nums[i - 1])
                i++;
        }
        return result;
    }
}